library(rgdal)
points <- readOGR('deepint.shp','deepint')
names(points)

library(lattice)
#trellis.par.set(sp.theme())
#spplot(points, "maxmag", do.log=T)

dt <- as.data.frame(points[,c(17,18,19,26)])
d <- dt[,1:4]

for (i in unique(d$MaxDepth)) {
    for (j in levels(d$Region)) {
        for (k in levels(d$Parameter)) {
            nr <- nrow(d)+1
            d[nr,] <- c(as.integer(i),as.double(1),k,j)
        }
    }
}

dagg <- aggregate(as.double(d$maxmag), by=list(d$Parameter,floor(as.double(d$MaxDepth)/2)*2, d$Region), max)
names(dagg) <- c("Parameter", "depth", "Region", "maxmag")



pdf("test.pdf",width=24,height=36)
#png("test.png",width=4000,height=3000)
y.lim = c(1,max(dagg$maxmag))

par(mar=c(12, 4.5, 2, 0.5),mfrow=c(length(unique(dagg$depth)),length(levels(dagg$Region))))

for (i in unique(dagg$depth)) {
    for (j in levels(dagg$Region)) {
        da <- dagg[dagg$Region==j & dagg$depth==i,]
        if (nrow(da)>0 & max(da$maxmag)>1) {
            barplot(da$maxmag,ylim=y.lim,names.arg=levels(da$Parameter),log="y",las=2,mar=4,
                    ylab="Maximum Magnitude of RBSL Exceedance", main=paste("Region",j,"@",i,"ft"))
        } else {
            frame()
        }
    }
}

dev.off()


